package com.gonsin.gnews.service;

import com.gonsin.gnews.NewsUtils;
import com.gonsin.gnews.annotations.exceptions.GNewsException;
import com.gonsin.gnews.annotations.model.*;
import com.gonsin.gnews.annotations.services.TemplateService;
import com.gonsin.gnews.mapper.NewsTemplateMapper;
import com.gonsin.i18n.logic.T;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Primary
public class NewsTemplateServiceImpl implements TemplateService {

    @Autowired private NewsTemplateMapper newsTemplateMapper;
    @Autowired private NewsCache cache;


    @Override
    public GNewsPageResult<NewsTemplateBean> searchTemplates(String edificeKey, NewsTemplateSearchPo searchPo, GNewsPageRequest pagePo) {
        List<NewsTemplateBean> list = newsTemplateMapper.searchTemplates(edificeKey, searchPo, NewsUtils.toPageable(pagePo));
        for(NewsTemplateBean newsTemplateBean : list){
            if(BooleanUtils.isTrue(newsTemplateBean.getInit())){
                newsTemplateBean.setContent(T.t(newsTemplateBean.getContent()));
            }
        }
        int count = newsTemplateMapper.countTemplates(edificeKey, searchPo);
        return GNewsPageResult.result(list, count, pagePo);
    }

    @Override
    public NewsTemplateBean getTemplate(String newsTemplateKey) {
        NewsTemplateBean newsTemplateBean = newsTemplateMapper.getTemplate(newsTemplateKey);
        if(BooleanUtils.isTrue(newsTemplateBean.getInit())){
            newsTemplateBean.setContent(T.t(newsTemplateBean.getContent()));
        }
        return newsTemplateBean;
    }

    @Override
    public void addNewsTemplate(String edificeKey, String templateKey, NewsTemplatePo po) {
        NewsTemplateBean bean = new NewsTemplateBean();
        bean.setPlatform(po.getPlatform());
        bean.setTemplateKey(templateKey);
        bean.setNewsTemplateKey(general("newsTemplate"));
        bean.setContent(po.getContent());
        bean.setName(po.getName());
        bean.setParams(po.getParams());
        bean.setSmsContent(po.getSmsContent());
        bean.setTitle(po.getTitle());
        bean.setUrl(po.getUrl());
        bean.setTemplateCode(po.getTemplateCode());
        bean.setEnable(po.getEnable() != null ? po.getEnable() : true);
        bean.setEdificeKey(edificeKey);
        bean.setInit(po.getInit());
        if(po.getSort() != 0){
            bean.setSort(po.getSort());
        }else{
            bean.setSort(newsTemplateMapper.getMaxSort(edificeKey) + 1);
        }
        bean.setDefaultContent(po.getDefaultContent());
        bean.setCreateTime(new Date());
        bean.setUpdateTime(bean.getCreateTime());
        bean.setVersion(1);
        newsTemplateMapper.insert(bean);
        cache.evict(edificeKey + "-" + templateKey);
    }

    /**
     * 生成一个新的key
     * @return
     */
    public static String general(String beanName){
        int length = 32 - beanName.length() - 1;
        return beanName + "_" +  RandomStringUtils.random(length, true, true);
    }

    @Override
    public void updateNewsTemplate(String newsTemplateKey, NewsTemplatePo po) {
        NewsTemplateBean bean = newsTemplateMapper.getTemplate(newsTemplateKey);
        bean.setPlatform(po.getPlatform());
        bean.setContent(po.getContent());
        bean.setName(po.getName());
        bean.setParams(po.getParams());
        bean.setSmsContent(po.getSmsContent());
        bean.setTitle(po.getTitle());
        bean.setTemplateCode(po.getTemplateCode());
        bean.setUrl(po.getUrl());
//        if(po.getInit() != null){
//            bean.setInit(po.getInit());
//        }else{
//            bean.setInit(false);
//        }
//        if(Objects.equals(bean.getPlatform(), "bulletin")){
//            if(Objects.equals(bean.getContent(), bean.getDefaultContent())){
//                bean.setInit(true);
//            }else{
//                bean.setInit(false);
//            }
//        }
        bean.setSort(po.getSort());
        bean.setUpdateTime(new Date());
        bean.setVersion(bean.getVersion() + 1);
        bean.setTemplateKey(po.getTemplateKey());
        newsTemplateMapper.update(bean);
        cache.evict(bean.getEdificeKey() + "-" + bean.getTemplateKey());
    }

    @Override
    @Transactional
    public NewsTemplateBean moveUpNewsTemplate(String newsTemplateKey){
        NewsTemplateBean template = newsTemplateMapper.getTemplate(newsTemplateKey);
        if(template == null){
            throw new GNewsException("查找不到该消息模板");
        }
        List<NewsTemplateBean> newsTemplateBeans = newsTemplateMapper.getLtSortNewsTemplate(
                template.getEdificeKey(),template.getSort()
        );
        if(newsTemplateBeans.isEmpty()){
            return template;
        }
        NewsTemplateBean targetTemplate = newsTemplateBeans.get(0);
        int sort = template.getSort();
        int targetSort = targetTemplate.getSort();
        template.setSort(targetSort);
        targetTemplate.setSort(sort);
        newsTemplateMapper.update(template);
        newsTemplateMapper.update(targetTemplate);
        return template;
    }

    @Override
    @Transactional
    public NewsTemplateBean moveDownNewsTemplate(String newsTemplateKey){
        NewsTemplateBean template = newsTemplateMapper.getTemplate(newsTemplateKey);
        if(template == null){
            throw new GNewsException("查找不到该消息模板");
        }
        List<NewsTemplateBean> newsTemplateBeans = newsTemplateMapper.getGtSortNewsTemplate(
                template.getEdificeKey(),template.getSort()
        );
        if(newsTemplateBeans.isEmpty()){
            return template;
        }
        NewsTemplateBean targetTemplate = newsTemplateBeans.get(0);
        int sort = template.getSort();
        int targetSort = targetTemplate.getSort();
        template.setSort(targetSort);
        targetTemplate.setSort(sort);
        newsTemplateMapper.update(template);
        newsTemplateMapper.update(targetTemplate);
        return template;
    }

    @Override
    @Transactional
    public void deleteNewsTemplate(List<String> newsTemplateKey) {
        List<NewsTemplateBean> templates = newsTemplateMapper.getTemplateBatch(newsTemplateKey);
        // 清除缓存
        templates.forEach(key -> {
            cache.evict(key.getEdificeKey() + "-" + key.getTemplateKey());
        });
        newsTemplateMapper.deleteBatch(newsTemplateKey);
    }

    @Override
    @Transactional
    public void enableTemplate(String newsTemplateKey, boolean enable) {
        // 查看是否有同类型的模板已经启用
        NewsTemplateBean template = newsTemplateMapper.getTemplate(newsTemplateKey);
        if(template == null){
            throw new GNewsException("查找不到该消息模板");
        }
        if(enable){
            template.setEnable(true);
            newsTemplateMapper.update(template);
            return;
        }

        template.setEnable(false);
        newsTemplateMapper.update(template);
        cache.evict(template.getEdificeKey() + "-" + template.getTemplateKey());
    }

}
